<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button
            v-allow="'import_excel'"
            type="warning"
            size="small"
            @click="$router.push('/import')"
          >excel导入</el-button>
          <el-button
            v-allow="'export_excel'"
            type="danger"
            size="small"
            @click="exportExcel"
          >excel导出</el-button>
          <el-button
            v-allow="'add'"
            type="primary"
            size="small"
            @click="dialogVisible=true"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table
          :data="list"
          border
          :default-sort="{prop: 'timeOfEntry', order: 'descending'}"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" width="100">
            <template #default="{row}">
              <img
                v-imgerror="'https://img0.baidu.com/it/u=874971431,3481772630&fm=253&fmt=auto&app=138&f=PNG?w=521&h=500'"
                :src="row.staffPhoto"
                alt=""
                style="width:100%"
                @click="showCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ fromData(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" prop=""/> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small" @click="assignRolelo(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delIcm(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="pageParams.page"
            :page-size="pageParams.size"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="30%"
      >
        <emplDialog @success="doSuccess" @close="dialogVisible=false" />
      </el-dialog>
      <el-dialog
        title="显示二维码"
        :visible.sync="showCodeDialog"
        width="30%"
      >
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>

      </el-dialog>
      <el-dialog
        title="分配角色"
        :visible.sync="assignRoleDialog"
        width="30%"
      >
        <assignRole
          v-if="assignRoleDialog"
          :cer-id="cerId"
          @success="assignRoleDialog=false"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import assignRole from './assignRole.vue'
import QRCode from 'qrcode'
import { delEmployees, getEmployees } from '@/api/employees'
import employees from '@/constant/employees'
import emplDialog from './emplDialog.vue'
const hireType = employees.hireType.reduce((sum, item) => {
  sum[item.id] = item.value
  return sum
}, {})
export default {
  name: 'VueHrEmployees',
  components: {
    emplDialog,
    assignRole
  },

  data() {
    return {
      list: [],
      pageParams: {
        page: 1, // 页码
        size: 500 // 每页的条数
      },
      total: 0,
      dialogVisible: false, // 控制弹窗
      showCodeDialog: false, // 控制二维码弹窗的显示和隐藏
      assignRoleDialog: false, // 控制的是分配角色的隐藏和显示
      cerId: '' // 点击分配角色获得的id值

    }
  },

  created() {
    this.loadEmployees()
  },

  methods: {
    // 点击分配角色触发的事件
    assignRolelo(id) {
      console.log(id)
      this.cerId = id
      this.assignRoleDialog = true
    },
    // 点击图片弹出二维码
    showCode(url) {
      if (url) {
        this.showCodeDialog = true
        // 生成二维码
        this.$nextTick(() => {
          const canvas = this.$refs.myCanvas
          // 生成二维码图片
          QRCode.toCanvas(canvas, url)
        })
      } else {
        this.$message.error('请点击正确的图片')
      }
    },
    exportExcel() {
    // import('@/vendor/Export2Excel')  懒加载的方式导入一个模块， 返回值是一个promise实例
      import('@/vendor/Export2Excel').then(excel => {
        // excel指的模块对象，那么就可以使用这个模块对象去调用这个模块里面的函数或者访问变量   excel.函数名()
        const { tHeader, data } = this.conversion(this.list)
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // console.log(list, 'listaaaaaaaaaaaaaaaaaaaa')
        // const data = this.formatJson(filterVal, list)
        // console.log(data, 'dataaaaaaaaaaaaaaaaa') // [[1,'三体','刘慈欣',100000,'2022-11-05'],[2,'西游记','吴承恩',100000,'1995-11-05']]
        // const data = [[1, '三体', '刘慈欣', 100000, '2022-11-05'], [2, '西游记', '吴承恩', 100000, '1995-11-05']]
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    conversion(list) {
      //    中引文的映射对象
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 创建一个数组 为表头
      const one = list[0] // undenfu || 有数据
      if (!one) return
      const tHeader = Object.keys(one).map(enkey => {
        return mapInfo[enkey]
      })
      // const Theader = Object.values(one)  // 拿到的是数组内的第一个元素的 值
      // console.log(Theader); // 拿到的是 mapInfo 内的 值

      // 生成表的内容
      const data = list.map(item => {
        return Object.values(item)
      })
      // console.log(data); // 拿到的是数组内的每一个元素对象内的 值
      return { tHeader, data }
    },

    // 删除员工
    delIcm(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // this.$message({
        //   type: 'success',
        //   message: '删除成功!'
        // })
        // 发送删除请求
        const res = await delEmployees(id)
        console.log(res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        if (this.list.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
        }
        this.loadEmployees()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    //
    doSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.pageParams.size)
      this.pageParams.page = maxPage
      // 关闭弹窗，重新渲染
      this.loadEmployees()
      this.dialogVisible = false
    },
    // 分页
    handleCurrentChange(val) {
      this.pageParams.page = val
      this.loadEmployees()
    },
    // 将 聘请方式内的 1改为正式 和 2改为非正式
    fromData(id) {
      // console.log(id) // row.formOfEmployment 内的 formOfEmployment 是指表格内的 1 和 2
      // return employees.hireType.find(item => item.id === id).value
      return hireType[id] || '未知'
    },
    // 发送获得员工信息列表的请求
    async loadEmployees() {
      try {
        const res = await getEmployees(this.pageParams)
        // console.log(res, 'loadEmployees')
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
